package com.mxm.mirai.tools;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 漫小猫工具类
 */
public class MXM_Tools {
    private static List<String> FILE_PATHS;
    private final static Set<String> PublicSuffixSet = new HashSet<String>(
            Arrays.asList(new String(
                    "com|org|net|gov|edu|co|tv|mobi|info|asia|xxx|onion|cn|com.cn|edu.cn|gov.cn|net.cn|org.cn|jp|kr|tw|com.hk|hk|com.hk|org.hk|se|com.se|org.se")
                    .split("\\|")));
    private final static Pattern IP_PATTERN = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");

    public static void main(String[] args){
        //System.out.println(M_UrlGet("http://api.brhsm.cn/lt.php?msg=你是",null,null,null));
    }
    /**
     * UUID去除-
     **/
    public static String M_UUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }
    /**
     * UUID去除-并加时间
     **/
    public static String M_UUID_Time(){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        return UUID.randomUUID().toString().replace("-", "")+sdf.format(d);
    }

    /**
     * 取随机数
     * @param min
     * @param max
     * @return
     */
    public static Integer M_Random(Integer min,Integer max){
        Random rand = new Random();
        return rand.nextInt(max)+ min;
    }
    /**
     * 读取文件内容
     * @param filePath
     * String 如 c:\\1.txt 绝对路径
     * @return boolean
     */
    public static String M_GetreadFile(String filePath) {
        StringBuffer fileContent = new StringBuffer();
        try {
            File f = new File(filePath);
            if (f.isFile() && f.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(f), "UTF-8");
                BufferedReader reader = new BufferedReader(read);
                String line;
                while ((line = reader.readLine()) != null) {
                    fileContent.append(line);
                }
                read.close();
            }
        } catch (Exception e) {
            System.out.println("读取文件内容操作出错");
            return null;
        }
        return fileContent.toString();
    }

    /**
     *文件写入内容
     * @Description: 写文件
     * @param @param filePath 文件路径
     * @param @param fileContent    文件内容
     * @throws
     */
    public static void  M_SetwriteFile(String filePath, String fileContent) {
        try {
            File f = new File(filePath);
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(fileContent);
            writer.close();
        } catch (Exception e) {
            System.out.println("写文件内容操作出错");
        }
    }

    /**
     * 截取字符串str中指定字符 strStart、strEnd之间的字符串
     *
     * @param str
     * @param strStart
     * @param strEnd
     * @return
     */
    public static String M_SubString(String str, String strStart, String strEnd) {
        /* 找出指定的2个字符在 该字符串里面的 位置 */
        int strStartIndex = str.indexOf(strStart);
        int strEndIndex = str.indexOf(strEnd);
        /* index 为负数 即表示该字符串中 没有该字符 */
        if (strStartIndex < 0) {
            return "字符串 :---->" + str + "<---- 中不存在 " + strStart + ", 无法截取目标字符串";
        }
        if (strEndIndex < 0) {
            return "字符串 :---->" + str + "<---- 中不存在 " + strEnd + ", 无法截取目标字符串";
        }
        /* 开始截取 */
        String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
        return result;
    }


    /**
     * http请求获取链接的后缀名
     * @param strUrl
     * @return
     */
    public static String M_parseSuffix(String strUrl) {
        BufferedInputStream bis = null;
        HttpURLConnection urlConnection = null;
        URL url = null;
        try {
            url = new URL(strUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            bis = new BufferedInputStream(urlConnection.getInputStream());
            return HttpURLConnection.guessContentTypeFromStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取url的主域名
     * @param url
     * @return
     */
    public static String M_GetURLName(String url){
        Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
        Matcher m = p.matcher(url);
        if(m.find()){
            return m.group();
        }
        return "获取失败";
    }
    /**
     * 获取url的顶级域名
     * @param urls
     * @return
     */
    public static String M_GetURLDomainName(String urls) {
        URL url = null;
        try {
            url = new URL(urls);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        String host = url.getHost();
        if (host.endsWith(".")){
            host = host.substring(0, host.length() - 1);
        }
        if (IP_PATTERN.matcher(host).matches()){
            return host;
        }
        int index = 0;
        String candidate = host;
        for (; index >= 0;) {
            index = candidate.indexOf('.');
            String subCandidate = candidate.substring(index + 1);
            if (PublicSuffixSet.contains(subCandidate)) {
                return candidate;
            }
            candidate = subCandidate;
        }
        return candidate;
    }
    /**
     * <p>
     *     获取系统本项目路径
     *     linux系统返回:项目名路径+/WEB-INF/classes/
     *     window系统war项目返回:项目名路径+\src\main\resources\
     *     window系统jar项目返回:项目名路径
     * </p>
     * @return
     */
    public static String M_GetSystemPath(){
        String filePath=null;
        if("/".equals(File.separator)){//判断系统linux否则win系统
            String classPath = MXM_Tools.class.getClassLoader().getResource("/").getPath();
            filePath = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
            filePath = filePath.replace("\\", "/");
            filePath = filePath+"/WEB-INF/classes/";
        }else {
            if(new File(System.getProperty("user.dir")+"/src/main").exists()){
                filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\";
            }else {
                filePath = System.getProperty("user.dir")+"\\";
            }
        }
        return filePath;
    }
    /**
     * 将文件流转换成Byte数组
     * @param pathStr
     * @return
     */
    public byte[] M_GetBytesByFile(String pathStr) {
        File file = new File(pathStr);
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 汉字转换成二进制字符串
     * @param str
     * @return
     */
    public static String M_StrToBinStr(String str) {
        char[] chars=str.toCharArray();
        StringBuffer result = new StringBuffer();
        for(int i=0; i<chars.length; i++) {
            result.append(Integer.toBinaryString(chars[i]));
            result.append(" ");
        }
        return result.toString();
    }

    /**
     * 二进制字符串转换成汉字
     * @param binary
     * @return
     */
    public static String M_BinStrTostr(String binary) {
        String[] tempStr=binary.split(" ");
        char[] tempChar=new char[tempStr.length];
        for(int i=0;i<tempStr.length;i++) {
            tempChar[i]=BinstrToChar(tempStr[i]);
        }
        return String.valueOf(tempChar);
    }
    //将二进制字符串转换成int数组
    public static int[] BinstrToIntArray(String binStr) {
        char[] temp=binStr.toCharArray();
        int[] result=new int[temp.length];
        for(int i=0;i<temp.length;i++) {
            result[i]=temp[i]-48;
        }
        return result;
    }

    //将二进制转换成字符
    public static char BinstrToChar(String binStr){
        int[] temp=BinstrToIntArray(binStr);
        int sum=0;
        for(int i=0; i<temp.length;i++){
            sum +=temp[temp.length-1-i]<<i;
        }
        return (char)sum;
    }

    /**
     * 中文转unicode编码
     * @param gbString
     * @return
     */
    public static String M_GbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /**
     * unicode编码转中文
     * @param dataStr
     * @return
     */
    public static String M_DecodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }
    /**
     * md5加密
     * @param md5
     * @return String
     */
    public static String M_Md5 (String md5) {
        // 生成一个MD5加密计算摘要
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update((md5+"mamsqxt").getBytes());
            // digest()最后确定返回md5 值hash，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            return md5;
        }// MD5 SHA-256...
    }
    /**
     * 时间差计算 A-B=n天
     * @param Adate A
     * @param Bdate B
     * @return int
     */
    public int M_DifferentDays( Date Adate,Date Bdate){
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(Bdate);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(Adate);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2){//同一年
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                if(i%4==0 && i%100!=0 || i%400==0){//闰年
                    timeDistance += 366;
                }else{ //不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }else{//不同年
            System.out.println("判断dayA - dayB : " + (day2-day1));
            return day2-day1;
        }
    }

    /**
     * 文件搜索方法,path(要搜索的文件路径),Suffix(要搜索什么格式的文件(比如.txt))
     * @param path
     * @param Suffix
     */
    public static List<String> M_SearchFile(String path, String Suffix) {
        File file = new File(path);
        String name = file.getName();
        boolean b = file.isDirectory();// 判断是否为文件夹
        if(b){// 是文件夹
            File[] files = file.listFiles();
            for(File f : files){
                M_SearchFile(f.getPath(),Suffix);
//                System.out.println(name);//打印文件夹名字
            }
        }else{
            if (name.indexOf(Suffix)!=-1) {
                FILE_PATHS.add(name);
            }
        }
        return FILE_PATHS;
    }
    /**
     * 图片水印
     * text：水印内容
     * file1：要水印图片地址
     * file2: 水印成功图片存放位置
     * @param text
     * @param file1
     * @param file2
     */
    public void M_ImageBySy(String text,String file1,String file2) {
        //使用JavaAPI获取一张图片
        BufferedImage b = null;
        try {
            b = ImageIO.read(new File(file1));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        //获取图片宽
        int width=b.getWidth();
        //获取图片高
        int height=b.getHeight();

        //画笔
        Graphics g = b.getGraphics();

//		g.setColor(Color.WHITE);
//		画笔为黑色为黑色
//		g.setColor(Color.BLACK);
//		把图片的边框画为黑色
//		g.drawRect(0, 0, width-1, height-1);

        Random r=new Random();
        Font f=new Font("微软雅黑", Font.BOLD, 32);//设置字体
        g.setFont(f);
        // 0-255
        int red = r.nextInt(256);
        int green = r.nextInt(256);
        int blue = r.nextInt(256);
        Color color=new Color(red, green, blue); //随机色
        g.setColor(color);
        g.drawString(text, (width/2)-32, (height/2)-32);
        try {
            ImageIO.write(b, "jpeg", new File(file2));
            System.out.println(text+"图片水印成功！");
        } catch (IOException e) {
            System.out.println(text+"图片水印失败！");
            e.printStackTrace();
        }
    }
    /**
     * 图片水印
     * text：水印内容
     * tx: 水印文字大小
     * file1：要水印图片地址
     * file2: 水印成功图片存放位置
     * @param text
     * @param tx
     * @param file1
     * @param file2
     */
    public void M_imageBySy(String text,Integer tx,String file1,String file2) {
        //使用JavaAPI获取一张图片
        BufferedImage b = null;
        try {
            b = ImageIO.read(new File(file1));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        //获取图片宽
        int width=b.getWidth();
        //获取图片高
        int height=b.getHeight();

        //画笔
        Graphics g = b.getGraphics();

//		g.setColor(Color.WHITE);
//		画笔为黑色为黑色
//		g.setColor(Color.BLACK);
//		把图片的边框画为黑色
//		g.drawRect(0, 0, width-1, height-1);

        Random r=new Random();
        Font f=new Font("微软雅黑", Font.BOLD, tx);//设置字体
        g.setFont(f);
        // 0-255
        int red = r.nextInt(256);
        int green = r.nextInt(256);
        int blue = r.nextInt(256);
        Color color=new Color(red, green, blue); //随机色
        g.setColor(color);
        g.drawString(text, (width/2)-32, (height/2)-32);
        try {
            ImageIO.write(b, "jpeg", new File(file2));
            System.out.println(text+"图片水印成功！");
        } catch (IOException e) {
            System.out.println(text+"图片水印失败！");
            e.printStackTrace();
        }
    }
    /**
     * 文件写出方法
     * @param text
     * @param file
     */
    public void M_TextSetFile(String text,String file) {
        File fp=new File(file);
        PrintWriter pfp = null;
        try {
            pfp = new PrintWriter(fp);
        } catch (FileNotFoundException e) {
            System.out.println("文件写出失败");
            e.printStackTrace();
        }
        pfp.print(text);
        pfp.close();
        System.out.println("文件写出到"+file+"成功！");
    }
    /**
     * 图片转ascii
     * path：图片路径
     * @param path
     */
    public static void M_ImageCreateAsciiPic(final String path) {
        final String base = "@#&$%*o!;.";// 字符串由复杂到简单
        try {
            final BufferedImage image = ImageIO.read(new File(path));
            for (int y = 0; y < image.getHeight(); y += 2) {
                for (int x = 0; x < image.getWidth(); x++) {
                    final int pixel = image.getRGB(x, y);
                    final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
                    final float gray = 0.299f * r + 0.578f * g + 0.114f * b;
                    final int index = Math.round(gray * (base.length() + 1) / 255);
                    System.out.print(index >= base.length() ? " " : String.valueOf(base.charAt(index)));
                }
                System.out.println();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * GET网页访问
     * @param urls
     * @return
     */
    public static String M_UrlGet(String urls,String cookie,String ua,String charsets) {
        StringBuffer jg = new StringBuffer();
        String charset = "UTF-8";
        if(null!=charsets){
            charset = charsets;
        }
        try {
            URL url = new URL(urls);
            System.out.println("URL 为：" + url.toString());
            System.out.println("协议为：" + url.getProtocol());
            System.out.println("验证信息：" + url.getAuthority());
            System.out.println("文件名及请求参数：" + url.getFile());
            System.out.println("主机名：" + url.getHost());
            System.out.println("路径：" + url.getPath());
            System.out.println("端口：" + url.getPort());
            System.out.println("默认端口：" + url.getDefaultPort());
            System.out.println("请求参数：" + url.getQuery());
            System.out.println("定位位置：" + url.getRef());
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时
            connection.setConnectTimeout(3*1000);
            //设置Cookie
            if(cookie!=null){
                connection.setRequestProperty("Cookie", cookie);
            }
            //设置请求头
            if(ua!=null){
                connection.setRequestProperty("User-Agent",ua);
            }else{
                connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            }

            //获取输入流
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());

            byte[] b = new byte[1024];
            int len = 0;

            while((len = bis.read(b)) != -1){
                jg.append(new String(b, 0, len,charset));
            }
            bis.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jg.toString();
    }
    /**
     * POST网页访问方法
     * urlPath:访问的URL
     * param:提交的post数据
     * cookie:设置Cookie
     * @param urlPath
     * @param param
     * @param cookie
     * @return
     */
    public static String M_URLPost(String urlPath,String param,String cookie) {
        try {
            //建立连接
            URL url=new URL(urlPath);
            HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
            //设置参数
            httpConn.setDoOutput(true);     //需要输出
            httpConn.setDoInput(true);      //需要输入
            httpConn.setUseCaches(false);   //不允许缓存
            httpConn.setRequestMethod("POST");      //设置POST方式连接

            //设置请求属性
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            //设置Cookie
            httpConn.setRequestProperty("Cookie", cookie);

            //连接,也可以不用明文connect，使用下面的httpConn.getOutputStream()会自动connect
            httpConn.connect();

            //建立输入流，向指向的URL传入参数
            DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());
            dos.writeBytes(param);
            dos.flush();
            dos.close();

            //获得响应状态
            int resultCode=httpConn.getResponseCode();
            if(HttpURLConnection.HTTP_OK==resultCode){
                StringBuffer sb=new StringBuffer();
                String readLine=new String();
                BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
                while((readLine=responseReader.readLine())!=null){
                    sb.append(readLine).append("\n");
                }
                responseReader.close();
//			    System.out.println(sb.toString());
                return sb.toString();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "请求失败！";
    }
    /**
     * 文件下载方法
     * fileUrl：文件下载的链接
     * fileName：保存的文件名
     * savePath：文件保存的位置
     * @param fileUrl
     * @param fileName
     * @param savePath
     * @throws Exception
     */
    public static void M_DownloadFileFromUrl(String fileUrl,String fileName,String savePath) throws Exception {
        //获取连接
        URL url=new URL(fileUrl);
        HttpURLConnection connection=(HttpURLConnection)url.openConnection();
        connection.setConnectTimeout(3*1000);
        //设置请求头
        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
        //获取输入流
        InputStream in=connection.getInputStream();

        File saveDir=new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdirs();
        }
        File file=new File(savePath+fileName);

        OutputStream out=new FileOutputStream(file);

        byte[] bytes=new byte[1024];
        int len=0;
        while((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
        out.close();
        in.close();
    }

    /**
     * 判断指定的文件是否存在。
     *
     * @param fileName
     * @return
     */
    public static boolean M_isFileExist(String fileName) {
        return new File(fileName).isFile();
    }

    /**
     * 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
     * 注意：可能会在返回false的时候创建部分父目录。
     *
     * @param file
     * @return
     */
    public static boolean M_makeDirectory(File file) {
        File parent = file.getParentFile();
        if (parent != null) {
            return parent.mkdirs();
        }
        return false;
    }

    /**
     * 返回文件的URL地址。
     *
     * @param file
     * @return
     * @throws MalformedURLException
     */
    public static URL M_getURL(File file) throws MalformedURLException {
        String fileURL = "file:/" + file.getAbsolutePath();
        URL url = new URL(fileURL);
        return url;
    }

    /**
     * 从文件路径得到文件名。
     *
     * @param filePath
     * @return
     */
    public static String M_getFileName(String filePath) {
        File file = new File(filePath);
        return file.getName();
    }

    /**
     * 从文件名得到文件绝对路径。
     *
     * @param fileName
     * @return
     */
    public static String M_getFilePath(String fileName) {
        File file = new File(fileName);
        return file.getAbsolutePath();
    }

    /**
     * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
     *
     * @param filePath
     * @return
     */
    public static String M_toUNIXpath(String filePath) {
        return filePath.replace("", "/");
    }

    /**
     * 从文件名得到UNIX风格的文件绝对路径。
     *
     * @param fileName
     * @return
     */
    public static String M_getUNIXfilePath(String fileName) {
        File file = new File(fileName);
        return M_toUNIXpath(file.getAbsolutePath());
    }

    /**
     * 得到文件后缀名
     *
     * @param fileName
     * @return
     */
    public static String M_getFileExt(String fileName) {
        int point = fileName.lastIndexOf('.');
        int length = fileName.length();
        if (point == -1 || point == length - 1) {
            return "";
        } else {
            return fileName.substring(point + 1, length);
        }
    }

    /**
     * 得到文件的名字部分。 实际上就是路径中的最后一个路径分隔符后的部分。
     *
     * @param fileName
     * @return
     */
    public static String M_getNamePart(String fileName) {
        int point = M_getPathLastIndex(fileName);
        int length = fileName.length();
        if (point == -1) {
            return fileName;
        } else if (point == length - 1) {
            int secondPoint = M_getPathLastIndex(fileName, point - 1);
            if (secondPoint == -1) {
                if (length == 1) {
                    return fileName;
                } else {
                    return fileName.substring(0, point);
                }
            } else {
                return fileName.substring(secondPoint + 1, point);
            }
        } else {
            return fileName.substring(point + 1);
        }
    }

    /**
     * 得到文件名中的父路径部分。 对两种路径分隔符都有效。 不存在时返回""。
     * 如果文件名是以路径分隔符结尾的则不考虑该分隔符，例如"/path/"返回""。
     *
     * @param fileName
     * @return
     */
    public static String M_getPathPart(String fileName) {
        int point = M_getPathLastIndex(fileName);
        int length = fileName.length();
        if (point == -1) {
            return "";
        } else if (point == length - 1) {
            int secondPoint = M_getPathLastIndex(fileName, point - 1);
            if (secondPoint == -1) {
                return "";
            } else {
                return fileName.substring(0, secondPoint);
            }
        } else {
            return fileName.substring(0, point);
        }
    }

    /**
     * 得到路径分隔符在文件路径中最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
     *
     * @param fileName
     * @return
     */
    public static int M_getPathLastIndex(String fileName) {
        int point = fileName.lastIndexOf("/");
        if (point == -1) {
            point = fileName.lastIndexOf("");
        }
        return point;
    }

    /**
     * 得到路径分隔符在文件路径中指定位置前最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
     *
     * @param fileName
     * @param fromIndex
     * @return
     */
    public static int M_getPathLastIndex(String fileName, int fromIndex) {
        int point = fileName.lastIndexOf("/", fromIndex);
        if (point == -1) {
            point = fileName.lastIndexOf("", fromIndex);
        }
        return point;
    }

    /**
     * 得到路径分隔符在文件路径中首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
     *
     * @param fileName
     * @return
     */
    public static int M_getPathIndex(String fileName) {
        int point = fileName.indexOf("/");
        if (point == -1) {
            point = fileName.indexOf("");
        }
        return point;
    }

    /**
     * 得到路径分隔符在文件路径中指定位置后首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
     *
     * @param fileName
     * @param fromIndex
     * @return
     */
    public static int M_getPathIndex(String fileName, int fromIndex) {
        int point = fileName.indexOf("/", fromIndex);
        if (point == -1) {
            point = fileName.indexOf("", fromIndex);
        }
        return point;
    }

    /**
     * 将文件名中的类型部分去掉。
     *
     * @param filename
     * @return
     */
    public static String M_removeFileExt(String filename) {
        int index = filename.lastIndexOf(".");
        if (index != -1) {
            return filename.substring(0, index);
        } else {
            return filename;
        }
    }

    /**
     * 得到相对路径。 文件名不是目录名的子节点时返回文件名。
     *
     * @param pathName
     * @param fileName
     * @return
     */
    public static String M_getSubpath(String pathName, String fileName) {
        int index = fileName.indexOf(pathName);
        if (index != -1) {
            return fileName.substring(index + pathName.length() + 1);
        } else {
            return fileName;
        }
    }

    /**
     * 删除一个文件。
     *
     * @param filename
     * @throws IOException
     */
    public static void M_deleteFile(String filename) throws IOException {
        File file = new File(filename);
        if (file.isDirectory()) {
            throw new IOException("IOException -> BadInputException: not a file.");
        }
        if (!file.exists()) {
            throw new IOException("IOException -> BadInputException: file is not exist.");
        }
        if (!file.delete()) {
            throw new IOException("Cannot delete file. filename = " + filename);
        }
    }

    /**
     * 删除文件夹及其下面的子文件夹
     *
     * @param dir
     * @throws IOException
     */
    public static void M_deleteDir(File dir) throws IOException {
        if (dir.isFile())
            throw new IOException("IOException -> BadInputException: not a directory.");
        File[] files = dir.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.isFile()) {
                    file.delete();
                } else {
                    M_deleteDir(file);
                }
            }
        }
        dir.delete();
    }

    /**
     * 复制文件
     *
     * @param src
     * @param dst
     * @throws Exception
     */
    public static void M_copy(File src, File dst) throws Exception {
        int BUFFER_SIZE = 4096;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                out = null;
            }
        }
    }

    /**
     * @复制文件，支持把源文件内容追加到目标文件末尾
     * @param src
     * @param dst
     * @param append
     * @throws Exception
     */
    public static void M_copy(File src, File dst, boolean append) throws Exception {
        int BUFFER_SIZE = 4096;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst, append), BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                out = null;
            }
        }
    }

}

